package com.wins.bbs.entity;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class PropertyMap {

    private boolean isInitialized = false;

    PropertyMap() {
        this.isInitialized = true;
    }

    Map<String, Object> convertObjToMap() {
        if (!this.isInitialized) return null;
        final Map<String, Object> propMap = new HashMap<>();
        try {
            final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass());
            final PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
            for (final PropertyDescriptor d : descriptors) {
                final Object o = d.getReadMethod().invoke(this);
                propMap.put(d.getDisplayName(), o);
            }
        } catch (final IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return propMap;
    }

    void setBeanValue(final String name, final Object value) {
        if (!this.isInitialized) return;
        try {
            final PropertyDescriptor descriptor = new PropertyDescriptor(name, this.getClass());
            final Method writeMethod = descriptor.getWriteMethod();
            writeMethod.invoke(this, value);

        } catch (final IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }


    Object getBeanValue(final String name) {
        if (!this.isInitialized) return null;
        try {
            final PropertyDescriptor descriptor = new PropertyDescriptor(name, this.getClass());
            final Method readMethod = descriptor.getReadMethod();
            return readMethod.invoke(this);

        } catch (final IntrospectionException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
